const failObj = {
	lat: "",
	lng: "",
	address: "",
	province: "",
	city: "",
	district: "",
	street: "",
	adcode: "",
	status: "fail",
};

import { getLocationInfo } from "@/API/common.js";
import stoarge from "./stoarge.js";

export default {
	/**
	 * 定位
	 * @param {Function} callback 回调函数
	 */
	getLocation(callback) {
		this.getAuthorize(callback);
	},
	/**
	 * 获取授权信息
	 */
	getAuthorize(callback) {
		let that = this;
		uni.authorize({
			scope: "scope.userLocation",
			success: (result) => {
				//用户同意授权
				that.getCurrentCoordition(callback);
			},
			fail: () => {
				//用户拒绝授权
				// that.openConfirm();
				this.stoargeLocation(failObj);
				callback & callback(failObj);
			},
		});
	},
	/**
	 * 当用户第一次拒绝后再次请求授权
	 */
	openConfirm() {
		let that = this;
		uni.showModal({
			title: "请求授权当前位置",
			content: "需要获取您的地理位置，请确认授权",
			success: (result) => {
				if (result.confirm) {
					//打开地图权限设置
					uni.openSetting();
				} else if (result.cancel) {
					uni.showToast({
						title: "你拒绝了授权，无法获取您的位置信息",
						icon: "none",
						duration: 1500,
					});
				}
			},
		});
	},
	/**
	 * 获取当前位置的经纬度
	 */
	getCurrentCoordition(callback) {
		uni.getLocation({
			type: "wgs84",
			success: (res) => {
				this.getCurrentAddress(res.latitude, res.longitude, callback);
			},
			fail: (err) => {
				this.stoargeLocation(failObj);
				callback & callback(failObj);
			},
		});
	},
	/**
	 * 获取当前城市信息
	 */
	getCurrentAddress(lat, lng, callback) {
		getLocationInfo(lat, lng)
			.then((res) => {
				let data = res.data;
				const province = data.province; //省
				const city = data.city; //市
				const district = data.district; //区
				const street = data.township; //街道
				const adcode = data.adcode; //adcode
				const address = province + city + district + street;
				let obj = {
					lat,
					lng,
					address,
					province,
					city,
					district,
					street,
					adcode,
					status: "success",
				};
				this.stoargeLocation(obj);

				callback & callback(obj);
			})
			.catch((res) => {
				failObj.lat = lat;
				failObj.lng = lng;
				this.stoargeLocation(failObj);
				callback & callback(failObj);
			});
	},
	/**
	 * 存储
	 */
	stoargeLocation(obj) {
		stoarge.setLocation(obj);
	},
};
